package com.example.demo.controller;

import com.example.demo.service.IShortLinkService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;

/**
 * @author chxbca
 */
@RestController
@RequiredArgsConstructor
@RequestMapping(path = "/link")
public class ShortLinkController {

    private final IShortLinkService shortLinkService;
    @Value("${host}")
    private String host;

    @GetMapping("/{shortCode}")
    public void redirect(@PathVariable("shortCode") String shortCode, HttpServletResponse httpServletResponse) {
        String longUrl = shortLinkService.convertLongLink(shortCode);
        httpServletResponse.setStatus(302);
        httpServletResponse.setHeader("Location", longUrl);
    }

    @PostMapping("/{longLink}")
    public String generateShortLink(@PathVariable("longLink") String LongLink) {
        return host + "link/" + shortLinkService.convertShortLink(LongLink);
    }

}
